package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.system.dtos.request.SysUserAddReq;
import com.rightsidetech.system.dtos.request.SysUserReq;
import com.rightsidetech.system.dtos.request.SysUserUpdateReq;
import com.rightsidetech.system.dtos.request.SysUserUpdateStatusReq;
import com.rightsidetech.system.dtos.response.SysRoleSelectResp;
import com.rightsidetech.system.dtos.response.SysUserResp;
import com.rightsidetech.system.entity.*;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysUserService;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-10-19 14:56
 */
@Slf4j
@Service("sysUserServiceImpl")
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserLoginInfoMapper sysUserLoginInfoMapper;
    @Resource
    private SysUserInfoMapper sysUserInfoMapper;
    @Resource
    private SysRoleAccountMapper sysRoleAccountMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysCompanyAreaMapper sysCompanyAreaMapper;

    @Override
    public ResponseData saveSyaAccount(SysUserAddReq sysUserAddReq, Long loginInfoId) throws Exception {
        //判断登录帐号是否重复
        SysUserLoginInfo userLoginInfo = sysUserLoginInfoMapper.selectByLoginName(sysUserAddReq.getLoginName());
        if (!ObjectUtils.isEmpty(userLoginInfo)) {
            return ResponseData.fail(CodeIdEnum.EXISTACCOUNT);
        }

        //判断角色是否存在
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(sysUserAddReq.getRoleId());
        if (ObjectUtils.isEmpty(sysRole)) {
            return ResponseData.fail(CodeIdEnum.NOROLE);
        }

        if (!ObjectUtils.isEmpty(sysUserAddReq.getAreaId()) && sysUserAddReq.getAreaId() != 0){
            SysCompanyArea area = sysCompanyAreaMapper.selectByPrimaryKey(sysUserAddReq.getAreaId());
            if (ObjectUtils.isEmpty(area)){
                return ResponseData.fail(CodeIdEnum.NOAREA);
            }
        }

        SysUserLoginInfo sysUserLoginInfo = new SysUserLoginInfo();
        sysUserLoginInfo.setLoginName(sysUserAddReq.getLoginName());
        sysUserLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
        sysUserLoginInfo.setPassword(DigestUtils.md5DigestAsHex((sysUserAddReq.getPassword() + sysUserLoginInfo.getSalt()).getBytes()));
        if(!StringUtils.isEmpty(sysUserAddReq.getAreaId())){
            sysUserLoginInfo.setSysCompanyAreaId(sysUserAddReq.getAreaId());
        }
        sysUserLoginInfoMapper.insertSelective(sysUserLoginInfo);

        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo.setLoginInfoId(sysUserLoginInfo.getId());
        sysUserInfo.setConnectWay(sysUserAddReq.getPhoneNo());
        sysUserInfo.setCreaterId(loginInfoId);
        sysUserInfo.setCreatedAt(new Date());
        sysUserInfo.setName(sysUserAddReq.getName());
        sysUserInfoMapper.insertSelective(sysUserInfo);

        //添加角色关联
        SysRoleAccount sysRoleAccount = new SysRoleAccount();
        sysRoleAccount.setCreatedAt(new Date());
        sysRoleAccount.setLoginInfoId(sysUserLoginInfo.getId());
        sysRoleAccount.setRoleId(sysUserAddReq.getRoleId());
        sysRoleAccount.setCreatedAt(new Date());
        sysRoleAccountMapper.insertSelective(sysRoleAccount);

        return ResponseData.success();
    }

    @Override
    public ResponseData updateSysAccount(SysUserUpdateReq sysUserUpdateReq, Long loginInfoId) throws Exception {
        SysUserLoginInfo sysUserLoginInfo = sysUserLoginInfoMapper.selectByPrimaryKey(sysUserUpdateReq.getLoginInfoId());
        if (sysUserLoginInfo == null) {
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }

        //判断角色是否存在
        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(sysUserUpdateReq.getRoleId());
        if (null == sysRole) {
            return ResponseData.fail(CodeIdEnum.NOROLE);
        }

        if (!ObjectUtils.isEmpty(sysUserUpdateReq.getAreaId()) && sysUserUpdateReq.getAreaId() != 0){
            SysCompanyArea area = sysCompanyAreaMapper.selectByPrimaryKey(sysUserUpdateReq.getAreaId());
            if (ObjectUtils.isEmpty(area)){
                return ResponseData.fail(CodeIdEnum.NOAREA);
            }
        }

        //判断是否存在重复的登录帐号
        SysUserLoginInfo sysUserLoginInfo1 = sysUserLoginInfoMapper.selectByLoginName(sysUserUpdateReq.getLoginName());
        if (null != sysUserLoginInfo1 && !sysUserLoginInfo1.getId().equals(sysUserLoginInfo.getId())) {
            return ResponseData.fail(CodeIdEnum.REPEATLOGIN);
        }

        sysUserLoginInfo = new SysUserLoginInfo();
        sysUserLoginInfo.setId(sysUserUpdateReq.getLoginInfoId());
        sysUserLoginInfo.setSysCompanyAreaId((long) 0);
        if (!ObjectUtils.isEmpty(sysUserUpdateReq.getAreaId())){
            sysUserLoginInfo.setSysCompanyAreaId(sysUserUpdateReq.getAreaId());
        }
        if (!StringUtils.isEmpty(sysUserUpdateReq.getLoginName())) {
            sysUserLoginInfo.setLoginName(sysUserUpdateReq.getLoginName());
        }
        if (!StringUtils.isEmpty(sysUserUpdateReq.getPassword())) {
            sysUserLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
            sysUserLoginInfo.setPassword(DigestUtils.md5DigestAsHex((sysUserUpdateReq.getPassword() + sysUserLoginInfo.getSalt()).getBytes()));
        }
        sysUserLoginInfoMapper.updateByPrimaryKeySelective(sysUserLoginInfo);

        SysUserInfo userInfo = new SysUserInfo();
        userInfo.setLoginInfoId(sysUserUpdateReq.getLoginInfoId());
        if (!StringUtils.isEmpty(sysUserUpdateReq.getPhoneNo())){
            userInfo.setConnectWay(sysUserUpdateReq.getPhoneNo());
        }
        if (!StringUtils.isEmpty(sysUserUpdateReq.getName())){
            userInfo.setName(sysUserUpdateReq.getName());
        }
        userInfo.setUpdaterId(loginInfoId);
        userInfo.setUpdatedAt(new Date());
        SysUserInfo sysUserInfo = sysUserInfoMapper.selectByLoginId(sysUserUpdateReq.getLoginInfoId());
        if (ObjectUtils.isEmpty(sysUserInfo)){
            userInfo.setCreaterId(loginInfoId);
            userInfo.setCreatedAt(new Date());
            sysUserInfoMapper.insertSelective(userInfo);
        } else {
            userInfo.setId(sysUserInfo.getId());
            sysUserInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        //添加/修改角色关联
        SysRoleAccount sysRoleAccount = sysRoleAccountMapper.selectByloginInfoId(sysUserUpdateReq.getLoginInfoId());
        if (null != sysRoleAccount) {
            sysRoleAccount.setRoleId(sysUserUpdateReq.getRoleId());
            sysRoleAccount.setUpdatedAt(new Date());
            sysRoleAccountMapper.updateByPrimaryKeySelective(sysRoleAccount);
        } else {
            sysRoleAccount = new SysRoleAccount();
            sysRoleAccount.setCreatedAt(new Date());
            sysRoleAccount.setLoginInfoId(sysUserUpdateReq.getLoginInfoId());
            sysRoleAccount.setRoleId(sysUserUpdateReq.getRoleId());
            sysRoleAccountMapper.insertSelective(sysRoleAccount);
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData deleteSysUserInfo(DelReq delReq) {
        SysUserLoginInfo sysUserLoginInfo = sysUserLoginInfoMapper.selectByPrimaryKey(delReq.getId());
        if (sysUserLoginInfo == null) {
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }

        sysUserLoginInfoMapper.updateIsDeletedInt((byte) 1, delReq.getId());
        sysUserInfoMapper.updateDel(delReq.getId());
        sysRoleAccountMapper.deleteByLoginId(delReq.getId());
        return ResponseData.success();
    }

    @Override
    public ResponseData<PageInfo<SysUserResp>> pageUserInfo(SysUserReq sysUserReq, Long loginInfoId) throws Exception {
        SysUserLoginInfo loginInfo = sysUserLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        PageHelper.startPage(sysUserReq.getPageNo(), sysUserReq.getPageSize());
        List<SysUserResp> list = sysUserLoginInfoMapper.selectSysUserList(sysUserReq,loginInfo.getSysCompanyAreaId());
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData updateStatus(SysUserUpdateStatusReq sysUserUpdateStatusReq) {
        SysUserLoginInfo sysUserLoginInfo2 = sysUserLoginInfoMapper.selectByPrimaryKey(sysUserUpdateStatusReq.getLoginInfoId());
        if (StringUtils.isEmpty(sysUserLoginInfo2)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

        SysUserLoginInfo sysUserLoginInfo = new SysUserLoginInfo();
        sysUserLoginInfo.setId(sysUserUpdateStatusReq.getLoginInfoId());
        sysUserLoginInfo.setStatus(sysUserUpdateStatusReq.getStatus());
        int count = sysUserLoginInfoMapper.updateByPrimaryKeySelective(sysUserLoginInfo);
        if (count <= 0) {
            return ResponseData.fail("修改记录为空");
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData<List<SysRoleSelectResp>> selectNameList(Long areaId) {
        return ResponseData.success(sysUserInfoMapper.selectNameList(areaId));
    }

    @Override
    public Long sysUsercheckToken(String token) {
        SysUserLoginHistory sysUserLoginHistory = sysUserLoginInfoMapper.selectLoginByToken(token);
        if (StringUtils.isEmpty(sysUserLoginHistory)){
            return null;
        }
        if (!StringUtils.isEmpty(sysUserLoginHistory.getLogoutTime())){
            return null;
        }else if (new Date().after (sysUserLoginHistory.getEffectiveTime())){
            return null;
        }
        return sysUserLoginHistory.getLoginInfoId();
    }

    @Override
    public SysUserLoginInfo selectUserById(Long loginId) {
        return sysUserLoginInfoMapper.selectByPrimaryKey(loginId);
    }

    @Override
    public SysUserResp selectById(Long id) {
        return sysUserLoginInfoMapper.selectById(id);
    }
}
